import request from '../../utils/request'

Page({
  data: {
    userInfo: null,
    tempFilePath: ''
  },

  onLoad() {
    this.setData({
      userInfo: wx.getStorageSync('userInfo')
    })
  },

  // 选择头像
  chooseAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          tempFilePath: res.tempFilePaths[0]
        })
        this.uploadAvatar()
      }
    })
  },

  // 上传头像
  uploadAvatar() {
    wx.uploadFile({
      url: 'YOUR_API_URL/upload',
      filePath: this.data.tempFilePath,
      name: 'file',
      success: (res) => {
        const data = JSON.parse(res.data)
        if (data.code === 0) {
          this.setData({
            'userInfo.avatarUrl': data.url
          })
        }
      }
    })
  },

  // 输入框变化
  handleInput(e) {
    const { field } = e.currentTarget.dataset
    this.setData({
      [`userInfo.${field}`]: e.detail.value
    })
  },

  // 保存资料
  async saveProfile() {
    try {
      const res = await request.put('/api/user/profile', this.data.userInfo)
      if (res.code === 0) {
        wx.setStorageSync('userInfo', this.data.userInfo)
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      }
    } catch (error) {
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      })
    }
  }
}) 